package pay.utils;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pay.portal.web.message.FM;
import pay.portal.web.message.UserChangeCardReqData;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FYApiUtil {
    protected static Logger logger = LoggerFactory.getLogger("FYApiUtil");

    public static String sendPostToFYUtils(Map<String, String> map,
                                           String jzhBaseUrl, String pathUrl) {
        URIBuilder builder = new URIBuilder().setScheme("https")
                .setHost(jzhBaseUrl).setPath(pathUrl);

        logger.info(builder.toString() + "");

        Map<String, String> trimmedParams = new HashMap<>();

        StringBuffer allUrl = new StringBuffer();

        for (String key : map.keySet()) {
            allUrl.append(map.get(key) + "|");
        }

        allUrl.setLength(allUrl.length() - 1);

        SecurityUtils.initPrivateKey();
        SecurityUtils.initPublicKey();
        String signature = SecurityUtils.sign(allUrl.toString());
        logger.info("富友请求拼接allUrl={},signature={}", allUrl, signature);
        for (String key : map.keySet()) {
            trimmedParams.put(key, map.get(key));
        }
        trimmedParams.put("signature", signature);
        String openResult = FYApiUtil.doPost(builder, trimmedParams);
        return openResult;
    }

    public static String doPost(URIBuilder builder,
                                Map<String, String> trimmedParams) {
        String result = "-1111";
        CloseableHttpResponse resp = null;
        CloseableHttpClient httpClient = null;
        try {
            URI uri = builder.build();
            RequestBuilder requestBuilder = RequestBuilder.post(uri);
            List<NameValuePair> kvs = new ArrayList<>();
            for (String key : trimmedParams.keySet()) {
                kvs.add(new BasicNameValuePair(key, trimmedParams.get(key)));
            }
            requestBuilder.setEntity(new UrlEncodedFormEntity(kvs, "UTF-8"));
            HttpUriRequest request = requestBuilder.build();

            httpClient = HttpClients.custom().setMaxConnPerRoute(200).build();
            resp = httpClient.execute(request);

            if (resp.getStatusLine().getStatusCode() >= 300) {
                logger.error("Something wrong: "
                        + resp.getStatusLine().toString());
            }
            BufferedReader input = new BufferedReader(new InputStreamReader(
                    resp.getEntity().getContent(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            char[] buf = new char[1000];
            int count;
            while ((count = input.read(buf)) > 0) {
                sb.append(buf, 0, count);
            }

            logger.info("返回结果如下sb={}", sb.toString());
            result = sb.toString();
            input.close();
        } catch (Exception e) {
            logger.error(" 方法异常！", e);
        } finally {
            try {
                if (resp != null) {
                    resp.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                logger.error("获取卡信息异常", e);
            }
        }

        return result;
    }


    public static String userChangeCard(UserChangeCardReqData userChangeCardReqData) throws Exception {

        if (userChangeCardReqData == null) {
            throw new Exception("请求参数为空");
        }
        String result = null;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;

        httpClient = HttpClients.createDefault();
        // 把一个普通参数和文件上传给下面这个地址 是一个servlet
        HttpPost httpPost = new HttpPost(userChangeCardReqData.getPathUrl());
        // 把文件转换成流对象FileBody

        FileBody bin = new FileBody(userChangeCardReqData.getFile1());
        FileBody bin2 = new FileBody(userChangeCardReqData.getFile2());
        StringBody binStr = new StringBody("", ContentType.create(
                "text/plain", Consts.UTF_8));
        StringBody bin2Str = new StringBody("", ContentType.create(
                "text/plain", Consts.UTF_8));


        StringBody mchnt_cd = new StringBody(userChangeCardReqData.getMchnt_cd(), ContentType.create(
                "text/plain", Consts.UTF_8));
        StringBody mchnt_txn_ssn = new StringBody(userChangeCardReqData.getMchnt_txn_ssn(), ContentType.create(
                "text/plain", Consts.UTF_8));
        StringBody login_id = new StringBody(userChangeCardReqData.getLogin_id(), ContentType.create(
                "text/plain", Consts.UTF_8));
        StringBody city_id = new StringBody(userChangeCardReqData.getCity_id(), ContentType.create(
                "text/plain", Consts.UTF_8));
        StringBody bank_cd = new StringBody(userChangeCardReqData.getBank_cd(), ContentType.create(
                "text/plain", Consts.UTF_8));
        StringBody card_no = new StringBody(userChangeCardReqData.getCard_no(), ContentType.create(
                "text/plain", Consts.UTF_8));


        SecurityUtils.initPrivateKey();
        SecurityUtils.initPublicKey();
        String signatureStr = SecurityUtils.sign(userChangeCardReqData.createSignValue());
        StringBody signature = new StringBody(signatureStr, ContentType.create(
                "text/plain", Consts.UTF_8));

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                // 相当于<input type="file" name="file"/>
                .addPart("file1", bin.getFilename().equals("") ? binStr : bin)
                .addPart("file2", bin2.getFilename().equals("") ? bin2Str : bin2)
                // 相当于<input type="text" name="userName" value=userName>
                .addPart("mchnt_cd", mchnt_cd)
                .addPart("mchnt_txn_ssn", mchnt_txn_ssn)
                .addPart("login_id", login_id)
                .addPart("city_id", city_id)
                .addPart("bank_cd", bank_cd)
                .addPart("card_no", card_no)
                .addPart("signature", signature)
                .build();
        httpPost.setEntity(reqEntity);
        // 发起请求 并返回请求的响应
        response = httpClient.execute(httpPost);


        if (response.getStatusLine().getStatusCode() >= 300) {
            logger.error("Something wrong: "
                    + response.getStatusLine().toString());
        }
        BufferedReader input = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent(), "UTF-8"));
        StringBuilder sb = new StringBuilder();
        char[] buf = new char[1000];
        int count;
        while ((count = input.read(buf)) > 0) {
            sb.append(buf, 0, count);
        }

        logger.info("返回结果如下sb={}", sb.toString());
        result = sb.toString();
        input.close();
        return result;

    }


    public static FM getBankCardInfo(String bankNo) {
        /* 全为生产 */
        URIBuilder builder = new URIBuilder().setScheme("https")
                .setHost("mpay.fuiou.com:16128")
                .setPath("/findPay/cardBinQuery.pay");
        Map<String, String> trimmedParams = new HashMap<>();
        String MchntCd = "0005810F0286174";
        String Ono = bankNo;
        String allUrl = MchntCd + "|" + Ono + "|"
                + "kxa9hmfeljw4g2531ne1e94zzp616d39";
        String Sign = MD5Crypter.md5Encrypt(allUrl);
        String fm = "<FM><MchntCd>" + MchntCd + "</MchntCd>" + "<Ono>" + Ono
                + "</Ono>" + "<Sign>" + Sign + "</Sign></FM> ";
        trimmedParams.put("FM", fm);
        String openResult = FYApiUtil.doPost(builder, trimmedParams);
        if ("-1111".equals(openResult)) {
            return null;
        } else {
            String result = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
                    + openResult.toLowerCase();
            BeanAndXMLTurn<FM> ff = new BeanAndXMLTurn<FM>();
            FM fmresultFm = ff.XMLStringToBean(result, new FM());
            return fmresultFm;
        }
    }

}
